//
//  UIViewController+Extension.swift
//  HinsLive
//
//  Created by haoxian on 2019/4/22.
//  Copyright © 2019 Hins. All rights reserved.
//

import UIKit


extension UIViewController {
    func safeDismiss(animated: Bool = true, completion: (() -> Void)? = nil) {
        DispatchQueue.safeMainAsync {
            self.dismiss(animated: animated, completion: completion)
        }
    }
    
    static func topViewController() -> UIViewController {
        guard var vc = UIApplication.shared.keyWindow?.rootViewController else { fatalError() }
        while true {
            if let tabbar = vc as? UITabBarController {
                guard let selected = tabbar.selectedViewController else { fatalError() }
                vc = selected
            }
            if let nav = vc as? UINavigationController {
                guard let last = nav.viewControllers.last else { fatalError() }
                vc = last
            }
            if let presented = vc.presentedViewController {
                vc = presented
            } else {
                break
            }
        }
        return vc
    }
}
